package com.jimmyc.fall12.OpenClass;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import android.app.Application;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

/* This will be used for global functions, constants and like the like
 * */

public class MyApplication extends Application {
	
	private final String TAG = "MyApplication";
	

	
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	private static MyApplication singleton;
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.v(TAG, "Hi from my application");
		singleton = this;
		Log.v(TAG, "End onCreat of myApplicatoin");
		
	}
	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}
	
	
	public MyApplication getInstance(){
		return singleton;
	}
	
	
	
	  public boolean isNetworkAvailable() {

			// from
			// http://stackoverflow.com/questions/4238921/android-detect-whether-there-is-an-internet-connection-available
			boolean haveConnectedWifi = false;
			boolean haveConnectedMobile = false;
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo[] netInfo = cm.getAllNetworkInfo();
			for (NetworkInfo ni : netInfo) {
				if (ni.getTypeName().equalsIgnoreCase("WIFI"))
					if (ni.isConnected())
						haveConnectedWifi = true;
				if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
					if (ni.isConnected())
						haveConnectedMobile = true;
			}
			return (haveConnectedWifi || haveConnectedMobile);
		
		}
	  
	//Must be done in the background, not UI thread
	  // <parameters sent to the task, ... , result of 
	private class DownloadWebPageTask extends AsyncTask <String, Void, String> {
		
		@Override
		protected String doInBackground(String... urls) {
			HttpContext localContext = new BasicHttpContext();
			HttpClient httpClient = new DefaultHttpClient();
			for (String url : urls) {
			HttpGet httpGet = new HttpGet(url);
			String result = "";
			try {
					HttpResponse response = httpClient.execute(httpGet, localContext);
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(
									response.getEntity().getContent()
									)
							);

					
					String line = "";
					while ((line = reader.readLine()) != null){
					
					result += line + "\n";
					
				}
					
					setDocument(result);
					return result;
			}		
			catch (Exception e) {
				e.printStackTrace();
				}
			
			}
			
			return ""; //should not have to get here
			
		}
		
		
		
		
	}
	/*Remember that for each time we want to download a webpage
	 * we must set the document string
	 * and also get the document string.
	 * They need be in sync!!!
	 * */
	private static String  document = "";
	
		private static void setDocument(String result) {
			document = result;
		}
		private static String getDocument() {
			return document;
		}
		

	
	//A simple function to get HTML source code in a string
	//TODO: Make into a boolean
	public String readWebpage(String url) {
		if (isNetworkAvailable() ) {
		    DownloadWebPageTask task = new DownloadWebPageTask();
		    task.execute(url);
		    //Synchronization problem. This is needed because I would like
		    //for the UI thread to wait
		    //for the AsyncTask to finish before continuing execution on UI thread
		    //a bit unsafe.. calls it after asyncTask doinBackground() is done, but
		    //not until whole task is finished executing...
		    
		    try {
		    	 task.get();
				////!!!! ony a temporary fix!!!!////
			} catch (InterruptedException e) {
			
				e.printStackTrace();
			} catch (ExecutionException e) {
			
				e.printStackTrace();
			}
		    
		    return getDocument();
		    
		 
		}
		else {
			return "";
			
		}
 }
}
